from scipy.sparse.linalg import *
import scipy.sparse as sp
import scipy
import utils
import numpy
from time import time
import argparse        
def pls(W, N, dx, dy, modelflag, trainsetflag):
    print 'pls %s %s' % (modelflag, trainsetflag);
    d = 100;
    print W.max(), W.min();
    U, S, VT = svds(W.transpose(),k=d,ncv=3*d, which='LM');

    D = sp.diags(S, 0, format='csc'); 
    Lx = sp.csr_matrix(U);
    #Lx = Lx.dot(D);
    Ly = sp.csr_matrix(VT.transpose());
    
    print type(Lx);

    print 'Saving Model For Batch %s %s' % (modelflag, trainsetflag);
    LxFile, LyFile = utils.spellModelName(modelflag, trainsetflag);
    utils.save_sparse_csr(LxFile, sp.csr_matrix(Lx));
    utils.save_sparse_csr(LyFile, sp.csr_matrix(Ly));

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='PLS algorithms');
    parser.add_argument('--modelflag', help= 'the runflag of this run');
    parser.add_argument('--trainsetflag', choices=['five', 'week', 'month'], default='five', help='specify the trainset');
    args = parser.parse_args();

    modelflag = args.modelflag;
    trainsetflag = args.trainsetflag;

    print modelflag, trainsetflag;  
    
    WName, NName = utils.spellWNSet(trainsetflag);
    start = time();
    config = utils.get_config();
    dx = config.getint('rmls', 'dx');
    dy = config.getint('rmls', 'dy');
    W = utils.load_sparse_csc(WName);
    N = 0;
    
    pls(W, N, dx, dy, modelflag, trainsetflag);

    print 'end:' + str(time() - start);
